<template>
  <div class="p-2">
    <!-- 统计卡片 -->
    <el-row :gutter="10" class="mb-4">
      <el-col :span="4">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">订单总数</div>
            <div class="stat-value">{{ statistics.total }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">待审核</div>
            <div class="stat-value text-warning">{{ statistics.auditing }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">待放款</div>
            <div class="stat-value text-primary">{{ statistics.disbursing }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">还款中</div>
            <div class="stat-value text-info">{{ statistics.repaying }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">已完成</div>
            <div class="stat-value text-success">{{ statistics.completed }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input
            v-model="queryParams.hospitalName"
            placeholder="请输入医院名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="放款状态" prop="loanStatus">
          <el-select v-model="queryParams.loanStatus" placeholder="请选择放款状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_loan_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['beauty:order:export']"
          >导出</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="orderList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单号" align="center" prop="orderNo" width="180" show-overflow-tooltip />
        <el-table-column label="项目名称" align="center" prop="projectName" width="150" show-overflow-tooltip />
        <el-table-column label="医院名称" align="center" prop="hospitalName" width="150" show-overflow-tooltip />
        <el-table-column label="订单总额" align="center" prop="totalAmount" width="120">
          <template #default="scope">
            {{ formatCurrency(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="首付金额" align="center" prop="downPayment" width="120">
          <template #default="scope">
            {{ formatCurrency(scope.row.downPayment) }}
          </template>
        </el-table-column>
        <el-table-column label="贷款金额" align="center" prop="loanAmount" width="120">
          <template #default="scope">
            {{ formatCurrency(scope.row.loanAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="分期期数" align="center" prop="periods" width="100">
          <template #default="scope">
            {{ scope.row.periods }}期
          </template>
        </el-table-column>
        <el-table-column label="月供金额" align="center" prop="monthlyAmount" width="120">
          <template #default="scope">
            {{ formatCurrency(scope.row.monthlyAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="orderStatus" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_order_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" fixed="right" width="350">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['beauty:order:query']"
            >详情</el-button>
            <el-button
              v-if="scope.row.contractId"
              link
              type="info"
              icon="Document"
              @click="handleViewContract(scope.row)"
              v-hasPermi="['beauty:contract:query']"
            >查看合同</el-button>
            <el-button
              v-if="scope.row.orderStatus === '0'"
              link
              type="success"
              @click="handleAudit(scope.row)"
              v-hasPermi="['beauty:order:audit']"
            >审核</el-button>
            <el-button
              v-if="scope.row.orderStatus === '1' && scope.row.loanStatus === '0'"
              link
              type="warning"
              @click="handleConfirmLoan(scope.row)"
              v-hasPermi="['beauty:order:loan']"
            >确认放款</el-button>
            <el-button
              v-if="scope.row.orderStatus !== '5' && scope.row.orderStatus !== '6'"
              link
              type="danger"
              @click="handleCancel(scope.row)"
              v-hasPermi="['beauty:order:cancel']"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog title="订单审核" v-model="auditDialog.visible" width="600px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="auditDialog.orderNo" disabled />
        </el-form-item>
        <el-form-item label="审核状态" prop="orderStatus">
          <el-radio-group v-model="auditForm.orderStatus">
            <el-radio v-for="dict in beauty_order_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            :rows="4"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="detailDialog.visible" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单ID">{{ detailDialog.data.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ detailDialog.data.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailDialog.data.userId }}</el-descriptions-item>
        <el-descriptions-item label="项目ID">{{ detailDialog.data.projectId }}</el-descriptions-item>
        <el-descriptions-item label="项目名称" :span="2">{{ detailDialog.data.projectName }}</el-descriptions-item>
        <el-descriptions-item label="医院ID">{{ detailDialog.data.hospitalId }}</el-descriptions-item>
        <el-descriptions-item label="医院名称">{{ detailDialog.data.hospitalName }}</el-descriptions-item>
        <el-descriptions-item label="医院地址" :span="2">{{ detailDialog.data.hospitalAddress }}</el-descriptions-item>
        <el-descriptions-item label="医院电话">{{ detailDialog.data.hospitalPhone }}</el-descriptions-item>
        <el-descriptions-item label="订单总额">{{ formatCurrency(detailDialog.data.totalAmount) }}</el-descriptions-item>
        <el-descriptions-item label="首付金额">{{ formatCurrency(detailDialog.data.downPayment) }}</el-descriptions-item>
        <el-descriptions-item label="贷款金额">{{ formatCurrency(detailDialog.data.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="分期期数">{{ detailDialog.data.periods }}期</el-descriptions-item>
        <el-descriptions-item label="利率">{{ detailDialog.data.interestRate }}%</el-descriptions-item>
        <el-descriptions-item label="月供金额">{{ formatCurrency(detailDialog.data.monthlyAmount) }}</el-descriptions-item>
        <el-descriptions-item label="总利息">{{ formatCurrency(detailDialog.data.totalInterest) }}</el-descriptions-item>
        <el-descriptions-item label="还款总额">{{ formatCurrency(detailDialog.data.totalRepayment) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="beauty_order_status" :value="detailDialog.data.orderStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="放款状态">
          <dict-tag :options="beauty_loan_status" :value="detailDialog.data.loanStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="银行卡ID">{{ detailDialog.data.cardId }}</el-descriptions-item>
        <el-descriptions-item label="银行卡号">{{ detailDialog.data.cardNo }}</el-descriptions-item>
        <el-descriptions-item label="开户银行">{{ detailDialog.data.bankName }}</el-descriptions-item>
        <el-descriptions-item label="合同ID">{{ detailDialog.data.contractId || '未生成' }}</el-descriptions-item>
        <el-descriptions-item label="合同状态">
          <el-tag v-if="detailDialog.data.contractStatus === '0'" type="warning">待签署</el-tag>
          <el-tag v-else-if="detailDialog.data.contractStatus === '1'" type="success">已签署</el-tag>
          <el-tag v-else-if="detailDialog.data.contractStatus === '2'" type="info">已失效</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="合同签署时间" :span="2">
          {{ detailDialog.data.contractSignatureTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="用户签名" :span="2">
          <el-image
            v-if="detailDialog.data.contractSignatureData"
            :src="detailDialog.data.contractSignatureData"
            :preview-src-list="[detailDialog.data.contractSignatureData]"
            style="width: 200px; height: 100px; border: 1px solid #dcdfe6; border-radius: 4px;"
            fit="contain"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ detailDialog.data.auditTime }}</el-descriptions-item>
        <el-descriptions-item label="放款时间">{{ detailDialog.data.loanTime }}</el-descriptions-item>
        <el-descriptions-item label="审核备注" :span="2">{{ detailDialog.data.auditRemark }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 合同查看对话框 -->
    <el-dialog title="合同详情" v-model="contractDialog.visible" width="900px">
      <el-descriptions :column="2" border v-if="contractDialog.data">
        <el-descriptions-item label="合同编号">{{ contractDialog.data.contractNo }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ contractDialog.data.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ contractDialog.data.userId }}</el-descriptions-item>
        <el-descriptions-item label="合同状态">
          <el-tag v-if="contractDialog.data.status === '0'" type="warning">待签署</el-tag>
          <el-tag v-else-if="contractDialog.data.status === '1'" type="success">已签署</el-tag>
          <el-tag v-else-if="contractDialog.data.status === '2'" type="info">已失效</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="借款金额">¥{{ formatCurrency(contractDialog.data.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="还款总额">¥{{ formatCurrency(contractDialog.data.totalRepayment) }}</el-descriptions-item>
        <el-descriptions-item label="分期期数">{{ contractDialog.data.periods }}期</el-descriptions-item>
        <el-descriptions-item label="月利率">{{ contractDialog.data.interestRate }}%</el-descriptions-item>
        <el-descriptions-item label="签署时间" :span="2">{{ contractDialog.data.signatureTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="合同条款" :span="2">
          <pre style="white-space: pre-wrap; max-height: 300px; overflow-y: auto; margin: 0;">{{ contractDialog.data.contractContent }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="用户签名" :span="2">
          <el-image
            v-if="contractDialog.data.signatureData"
            :src="contractDialog.data.signatureData"
            :preview-src-list="[contractDialog.data.signatureData]"
            style="width: 200px; height: 100px; border: 1px solid #dcdfe6; border-radius: 4px;"
            fit="contain"
          />
          <span v-else>-</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="contractDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleExportContractPdf(contractDialog.data.contractId, contractDialog.data.contractNo)">导出PDF</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BeautyOrder">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import {
  listOrder,
  getOrder,
  auditOrder,
  confirmLoan,
  cancelOrder,
  getOrderStatistics,
  exportOrder
} from '@/api/beauty/order';
import { getContract, exportContractPdf } from '@/api/beauty/contract';
import type { OrderQuery, OrderVO, AuditOrderRequest, OrderStatistics } from '@/api/beauty/order';
import { download } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { beauty_order_status, beauty_loan_status } = toRefs<any>(proxy?.useDict('beauty_order_status', 'beauty_loan_status'));

const loading = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const orderList = ref<OrderVO[]>([]);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const auditFormRef = ref<InstanceType<typeof ElForm>>();

const queryParams = ref<OrderQuery>({
  pageNum: 1,
  pageSize: 10,
  orderNo: undefined,
  projectName: undefined,
  hospitalName: undefined,
  orderStatus: undefined,
  loanStatus: undefined
});

const statistics = ref<OrderStatistics>({
  total: 0,
  auditing: 0,
  contract_signing: 0,
  disbursing: 0,
  repaying: 0,
  completed: 0
});

const auditDialog = reactive({
  visible: false,
  orderNo: '',
  orderId: 0
});

const detailDialog = reactive({
  visible: false,
  data: {} as OrderVO
});

const contractDialog = reactive({
  visible: false,
  data: {} as any
});

const auditForm = ref<AuditOrderRequest>({
  orderId: 0,
  orderStatus: '1',
  auditRemark: ''
});

const auditRules = reactive({
  orderStatus: [
    { required: true, message: '审核状态不能为空', trigger: 'change' }
  ]
});

// 获取订单统计
function getStatistics() {
  getOrderStatistics().then((response: any) => {
    statistics.value = response.data;
  });
}

// 查询订单列表
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then((response: any) => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: OrderVO[]) {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 订单详情
function handleDetail(row: OrderVO) {
  getOrder(row.orderId).then((response: any) => {
    detailDialog.data = response.data;
    detailDialog.visible = true;
  });
}

// 审核按钮操作
function handleAudit(row: OrderVO) {
  auditDialog.orderNo = row.orderNo;
  auditDialog.orderId = row.orderId;
  auditForm.value = {
    orderId: row.orderId,
    orderStatus: '1',
    auditRemark: ''
  };
  auditDialog.visible = true;
}

// 提交审核
function submitAudit() {
  auditFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      auditOrder(auditForm.value).then(() => {
        ElMessage.success('审核成功');
        auditDialog.visible = false;
        getList();
        getStatistics();
      });
    }
  });
}

// 确认放款
function handleConfirmLoan(row: OrderVO) {
  ElMessageBox.confirm('确认对订单"' + row.orderNo + '"进行放款操作吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return confirmLoan(row.orderId);
  }).then(() => {
    getList();
    getStatistics();
    ElMessage.success('放款成功');
  });
}

// 取消订单
function handleCancel(row: OrderVO) {
  ElMessageBox.confirm('确认要取消订单"' + row.orderNo + '"吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return cancelOrder(row.orderId);
  }).then(() => {
    getList();
    getStatistics();
    ElMessage.success('取消成功');
  });
}

// 查看合同
async function handleViewContract(row: OrderVO) {
  try {
    const res = await getContract(row.contractId);
    contractDialog.data = res.data;
    contractDialog.visible = true;
  } catch (error) {
    ElMessage.error('获取合同信息失败');
  }
}

// 导出合同PDF
async function handleExportContractPdf(contractId: number, contractNo: string) {
  try {
    const res = await exportContractPdf(contractId);
    const blob = new Blob([res], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${contractNo}.pdf`;
    link.click();
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出失败');
  }
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有订单数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return exportOrder(queryParams.value);
  }).then((response: any) => {
    download.excel(response, '订单数据.xlsx');
    ElMessage.success('导出成功');
  }).catch(() => {
    ElMessage.error('导出失败');
  });
}

// 获取订单状态文本
function getOrderStatusText(status: string): string {
  const statusMap: Record<string, string> = {
    '0': '待审核',
    '1': '审核通过',
    '2': '审核拒绝',
    '3': '已放款',
    '4': '还款中',
    '5': '已完成',
    '6': '已取消'
  };
  return statusMap[status] || '未知';
}

// 获取订单状态类型
function getOrderStatusType(status: string): string {
  const typeMap: Record<string, string> = {
    '0': 'warning',
    '1': 'success',
    '2': 'danger',
    '3': 'primary',
    '4': 'info',
    '5': 'success',
    '6': 'info'
  };
  return typeMap[status] || '';
}

// 格式化金额
function formatCurrency(amount: number | string | null | undefined): string {
  if (amount === null || amount === undefined || amount === '') return '-';
  const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
  if (isNaN(numAmount)) return '-';
  return '¥' + numAmount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}

onMounted(() => {
  getList();
  getStatistics();
});
</script>

<style scoped lang="scss">
.stat-card {
  text-align: center;
  padding: 10px 0;

  .stat-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;

    &.text-warning {
      color: #e6a23c;
    }

    &.text-primary {
      color: #409eff;
    }

    &.text-info {
      color: #909399;
    }

    &.text-success {
      color: #67c23a;
    }
  }
}
</style>
